'use strict';
const fs = require('fs'),iconv = require('iconv-lite');

module.exports = (request, response, rfun)=>{
    let path = request.SITE["root"] + request.GET.pathname;
    if(request.EXT) path += request.EXT;

    //request.LOG.error("loadByData", path);
    fs.stat(path, function(err, stats){
        if(!response.headersSent){
            if(request.CODE) response.setHeader("Content-Type", "text/html;charset="+request.CODE);
            else response.setHeader("Content-Type", "text/html;charset=UTF-8");
        } 
        if(err){
            request.LOG.error("loadByData", path, err);
            return;
        }
        if(stats.isDirectory()) path += "/index.html";
        fs.readFile(path, (err, data) => {
            if(err){
                request.LOG.error("loadByData read", path, err);
                return;
            }
            if(request.CODE) data = iconv.decode(data, request.CODE);
            data = data.toString();
            for(var k in response.DATA){
                data = data.replace(new RegExp("\\{\\{"+k+"\\}\\}", 'g'), response.DATA[k]);
            }
            if(request.CODE) data = iconv.encode(data, request.CODE);
            response.end(data);
            rfun();
        });
    });
}